<template>
  <div class="daily-page">
    <!-- 导航栏 -->
    <van-nav-bar 
      title="每日一句" 
      left-arrow 
      @click-left="handleBack"
    />

    <div class="daily-content">
      <!-- 日期显示 -->
      <div class="date-section">
        <div class="date-card">
          <div class="date-text">{{ currentDate }}</div>
          <div class="date-subtitle">今日练习</div>
        </div>
      </div>

      <!-- 每日一句内容 -->
      <div class="sentence-section">
        <div class="sentence-card">
          <div class="sentence-header">
            <van-icon name="volume-o" class="sentence-icon" />
            <span class="sentence-title">每日一句</span>
          </div>
          
          <div class="sentence-content">
            <div class="chinese-text">{{ dailySentence?.chinese || defaultSentence.chinese }}</div>
            <div class="pinyin-text">{{ dailySentence?.pinyin || defaultSentence.pinyin }}</div>
          </div>

          <!-- 播放按钮 -->
          <div class="play-section">
            <van-button
              type="primary"
              :icon="isPlaying ? 'pause-circle-o' : 'play-circle-o'"
              size="large"
              @click="playAudio"
              :loading="false"
              :disabled="!dailySentence?.audioUrl"
            >
              {{ isPlaying ? '停止播放' : '听发音' }}
            </van-button>
            <p v-if="!dailySentence?.audioUrl" class="audio-tips">
              暂无音频文件
            </p>
          </div>
        </div>
      </div>

      <!-- 录制区域 -->
      <div class="record-section">
        <div class="record-card">
          <div class="record-header">
            <van-icon name="video-o" class="record-icon" />
            <span class="record-title">视频提交</span>
          </div>

          <div class="record-content">
            <div class="record-tips">
              <p>📝 请跟读上面的句子</p>
              <p>� 录制您的朗读语音</p>
              <p>⭐ 提交后可获得评分</p>
            </div>

            <!-- 录制状态显示 -->
            <div class="record-status" v-if="recordStatus">
              <van-icon :name="recordStatus.icon" :color="recordStatus.color" />
              <span :style="{ color: recordStatus.color }">{{ recordStatus.text }}</span>
            </div>

            <!-- 视频上传区域 -->
            <div class="video-upload-section">
              <!-- 文件选择器 -->
              <input
                ref="videoInput"
                type="file"
                accept="video/*"
                @change="handleVideoSelect"
                style="display: none;"
              />

              <!-- 上传按钮 -->
              <div v-if="!selectedVideo" class="upload-button-container">
                <van-button
                  type="primary"
                  icon="video-o"
                  size="large"
                  @click="selectVideo"
                  block
                >
                  选择视频文件
                </van-button>
                <p class="upload-tips">支持 MP4、MOV、AVI 等格式，最大 50MB</p>
                <p v-if="videoDuration > 0" class="upload-tips" style="color: #1989fa;">视频时长：{{ formatDuration(videoDuration) }}</p>
              </div>

              <!-- 视频预览 -->
              <div v-if="selectedVideo" class="video-preview-section">
                <div class="video-info">
                  <van-icon name="video-o" color="#1989fa" />
                  <span class="video-name">{{ selectedVideo.name }}</span>
                  <div class="video-details">
                    <span class="video-size">{{ formatFileSize(selectedVideo.size) }}</span>
                    <span v-if="videoDuration > 0" class="video-duration">{{ formatDuration(videoDuration) }}</span>
                  </div>
                </div>

                <!-- 视频预览播放器 -->
                <video
                  ref="videoPreview"
                  :src="videoPreviewUrl"
                  class="video-preview"
                  controls
                  playsinline
                ></video>

                <!-- 操作按钮 -->
                <div class="video-actions">
                  <van-button
                    type="default"
                    icon="replay"
                    @click="reSelectVideo"
                    style="margin-right: 3vw;"
                  >
                    重新选择
                  </van-button>
                  <van-button
                    type="primary"
                    icon="success"
                    @click="submitVideo"
                    :loading="isSubmitting"
                  >
                    {{ isSubmitting ? '上传中...' : '提交视频' }}
                  </van-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 历史记录 -->
      <div class="history-section">
        <div class="section-header">
          <h3>历史记录</h3>
          <van-button type="primary" plain size="small" @click="viewAllHistory">
            查看全部
          </van-button>
        </div>

        <!-- 统计信息 -->
        <div v-if="historyStatistics" class="statistics-section">
          <div class="stat-item">
            <span class="stat-label">总记录</span>
            <span class="stat-value">{{ historyStatistics.totalRecords }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">平均分</span>
            <span class="stat-value">{{ historyStatistics.averageScore }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">最高分</span>
            <span class="stat-value">{{ historyStatistics.bestScore }}</span>
          </div>
        </div>

        <div v-if="historyList.length === 0" class="empty-history">
          <van-empty description="暂无历史记录" />
        </div>

        <div v-else class="history-list">
          <div
            v-for="record in historyList.slice(0, 3)"
            :key="record.id"
            class="history-item"
            @click="viewRecord(record)"
          >
            <div class="history-content">
              <div class="history-sentence">{{ record.sentence }}</div>
              <div class="history-date">{{ formatDate(record.createdAt) }}</div>
            </div>
            <div class="history-score">
              <van-tag :type="getScoreType(record.score)" class="score-tag">
                {{ record.score }}分
              </van-tag>
              <span class="level-badge" :class="getLevelClass(record.level)">
                {{ record.level }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="DailyPage" lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { DailyService } from '@/api/services';
import { getSupportedAudioFormat, ensureCompatibleFormat } from '@/utils/audioConverter';
import { createAudioPlayer, type AudioPlayer } from '@/utils/audioPlayer';
import type { DailySentence, DailyHistory } from '@/api/index';

const router = useRouter();

// 当前日期
const currentDate = ref('');

// 每日一句数据
const dailySentence = ref<DailySentence | null>(null);
const loading = ref(false);

// 默认数据
const defaultSentence: DailySentence = {
  id: 1,
  date: new Date().toISOString().split('T')[0],
  chinese: '学而时习之，不亦说乎？',
  pinyin: 'xué ér shí xí zhī, bù yì yuè hū?',
  english: 'Is it not a pleasure, having learned something, to try it out at due intervals?',
  source: '论语',
  audioUrl: '',
  difficulty: 'medium',
  category: 'classic',
  tags: ['经典', '学习']
};

// 音频播放状态
const isPlaying = ref(false);
const isPlayingRecorded = ref(false);

// 录制相关状态
const isRecording = ref(false);
const hasRecorded = ref(false);
const isSubmitting = ref(false);
const recordTime = ref(0);
const recordTimer = ref<number | null>(null);
const recordedBlob = ref<Blob | null>(null);
const mediaRecorder = ref<MediaRecorder | null>(null);
const audioChunks = ref<Blob[]>([]);

// 录制状态显示
const recordStatus = ref<{icon: string, color: string, text: string} | null>(null);

// 视频上传相关状态
const selectedVideo = ref<File | null>(null);
const videoPreviewUrl = ref<string>('');
const videoInput = ref<HTMLInputElement>();
const videoPreview = ref<HTMLVideoElement>();
const videoDuration = ref<number>(0);
const uploadedVideoUrl = ref<string>('');

// 历史记录
const historyList = ref<DailyHistory[]>([]);
const historyStatistics = ref<{
  totalRecords: number;
  averageScore: string;
  bestScore: string;
} | null>(null);

// 加载每日一句数据
const loadDailySentence = async (date?: string) => {
  try {
    loading.value = true;
    const data = await DailyService.getDailySentence(date);

    if (data) {
      dailySentence.value = data;
    } else {
      dailySentence.value = defaultSentence;
    }
  } catch (error) {
    console.error('加载每日一句失败:', error);
    dailySentence.value = defaultSentence;
  } finally {
    loading.value = false;
  }
};

// 加载历史记录
const loadHistory = async () => {
  try {
    console.log('🔄 开始加载历史记录...');
    const response = await DailyService.getDailyHistory({ page: 1, limit: 10 });
    console.log('📊 历史记录响应:', response);

    if (response && response.list) {
      historyList.value = response.list;
      console.log('✅ 历史记录列表加载成功:', response.list);
    }

    // 处理统计信息 - 根据API响应结构，统计信息在 message.statistics 中
    if (response && response.statistics) {
      historyStatistics.value = {
        totalRecords: response.statistics.totalRecords,
        averageScore: response.statistics.averageScore,
        bestScore: response.statistics.bestScore
      };
      console.log('✅ 统计信息加载成功:', historyStatistics.value);
    }
  } catch (error) {
    console.error('❌ 加载历史记录失败:', error);
  }
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 音频播放器实例
const audioPlayer = ref<AudioPlayer | null>(null);

// 播放音频
const playAudio = async () => {
  if (!dailySentence.value?.audioUrl) {
    showToast('暂无音频文件');
    return;
  }

  if (isPlaying.value) {
    // 如果正在播放，则停止播放
    stopAudio();
    return;
  }

  try {
    console.log('🎵 开始播放音频:', dailySentence.value.audioUrl);

    // 停止之前的音频
    if (audioPlayer.value) {
      audioPlayer.value.destroy();
    }

    // 创建新的音频播放器实例
    audioPlayer.value = createAudioPlayer(
      {
        volume: 1,
        preload: 'metadata'
      },
      {
        onLoadStart: () => {
          console.log('🔄 音频开始加载...');
        },
        onCanPlay: () => {
          console.log('✅ 音频可以播放');
        },
        onPlay: () => {
          console.log('▶️ 音频开始播放');
          isPlaying.value = true;
        },
        onPause: () => {
          console.log('⏸️ 音频暂停');
          isPlaying.value = false;
        },
        onEnded: () => {
          console.log('🏁 音频播放结束');
          isPlaying.value = false;
        },
        onError: (error) => {
          console.error('❌ 音频播放错误:', error);
          isPlaying.value = false;
          showToast('音频播放失败，请检查网络连接');
        }
      }
    );

    // 加载并播放音频
    await audioPlayer.value.load(dailySentence.value.audioUrl);
    await audioPlayer.value.play();

    showToast('正在播放标准发音');

  } catch (error: any) {
    console.error('❌ 播放音频失败:', error);
    isPlaying.value = false;

    if (error.name === 'NotAllowedError') {
      showToast('请允许音频播放权限');
    } else if (error.name === 'NotSupportedError') {
      showToast('音频格式不支持');
    } else if (error.message?.includes('网络')) {
      showToast('网络连接失败，请检查网络');
    } else {
      showToast('音频播放失败，请重试');
    }
  }
};

// 停止音频播放
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.stop();
  }
  isPlaying.value = false;
  console.log('⏹️ 停止音频播放');
};

// 播放录制的音频
const playRecordedAudio = () => {
  if (!recordedBlob.value) {
    showToast('没有录制的音频');
    return;
  }

  isPlayingRecorded.value = true;

  try {
    const audioUrl = URL.createObjectURL(recordedBlob.value);
    const audio = new Audio(audioUrl);

    audio.onended = () => {
      isPlayingRecorded.value = false;
      URL.revokeObjectURL(audioUrl);
    };

    audio.onerror = () => {
      isPlayingRecorded.value = false;
      URL.revokeObjectURL(audioUrl);
      showToast('音频播放失败');
    };

    audio.play().catch(() => {
      isPlayingRecorded.value = false;
      URL.revokeObjectURL(audioUrl);
      showToast('音频播放失败');
    });

  } catch (error) {
    isPlayingRecorded.value = false;
    showToast('音频播放失败');
  }
};

// 开始录制
const startRecording = async () => {
  try {
    // 请求麦克风权限
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        sampleRate: 44100
      }
    });

    // 获取最佳的录音格式
    const audioFormat = getSupportedAudioFormat();
    console.log('选择的录音格式:', audioFormat);

    const options: MediaRecorderOptions = audioFormat.mimeType ? {
      mimeType: audioFormat.mimeType
    } : {};

    mediaRecorder.value = new MediaRecorder(stream, audioFormat.mimeType ? options : undefined);
    audioChunks.value = [];

    // 设置录制事件
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        audioChunks.value.push(event.data);
      }
    };

    mediaRecorder.value.onstop = () => {
      // 创建音频Blob
      const mimeType = mediaRecorder.value?.mimeType || audioFormat.mimeType || 'audio/mp4';
      recordedBlob.value = new Blob(audioChunks.value, { type: mimeType });

      console.log('录制完成，音频格式:', mimeType);
      console.log('音频文件大小:', recordedBlob.value?.size);

      // 停止所有音频轨道
      stream.getTracks().forEach(track => track.stop());
    };

    // 开始录制
    mediaRecorder.value.start(1000); // 每秒收集一次数据

    isRecording.value = true;
    recordTime.value = 0;
    recordStatus.value = {
      icon: 'volume-o',
      color: '#ff4444',
      text: '正在录音中...'
    };

    // 开始计时
    recordTimer.value = window.setInterval(() => {
      recordTime.value++;
    }, 1000);

    showToast('开始录音');

  } catch (error) {
    console.error('录音初始化失败:', error);

    if (error.name === 'NotAllowedError') {
      showDialog({
        title: '麦克风权限被拒绝',
        message: '请在浏览器设置中允许此网站访问麦克风权限，然后刷新页面重试'
      });
    } else if (error.name === 'NotFoundError') {
      showDialog({
        title: '未找到麦克风',
        message: '请检查您的设备是否连接了麦克风'
      });
    } else {
      showToast('录音初始化失败，请重试');
    }
  }
};

// 停止录制
const stopRecording = () => {
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    mediaRecorder.value.stop();
  }

  isRecording.value = false;
  hasRecorded.value = true;

  if (recordTimer.value) {
    clearInterval(recordTimer.value);
    recordTimer.value = null;
  }

  recordStatus.value = {
    icon: 'success',
    color: '#07c160',
    text: `录音完成 (${recordTime.value}秒)`
  };

  showToast('录音完成');
};

// 重新录制
const reRecord = () => {
  hasRecorded.value = false;
  recordTime.value = 0;
  recordStatus.value = null;
  recordedBlob.value = null;
  audioChunks.value = [];
};

// 提交录制
const submitRecording = async () => {
  console.log('开始提交录音...');

  if (!recordedBlob.value || !dailySentence.value) {
    showToast('请先录音');
    return;
  }

  console.log('录音文件信息:', {
    size: recordedBlob.value.size,
    type: recordedBlob.value.type,
    duration: recordTime.value
  });

  isSubmitting.value = true;

  try {
    console.log('开始处理音频文件...');

    // 确保音频格式符合后端要求
    const originalExtension = recordedBlob.value.type.includes('mp3') ? 'mp3' :
                             recordedBlob.value.type.includes('wav') ? 'wav' :
                             recordedBlob.value.type.includes('m4a') ? 'm4a' :
                             recordedBlob.value.type.includes('mp4') ? 'mp4' : 'wav';

    console.log('原始音频格式:', recordedBlob.value.type);

    const { blob: compatibleBlob, extension } = await ensureCompatibleFormat(
      recordedBlob.value,
      originalExtension
    );

    const filename = `daily_${dailySentence.value.id}_${Date.now()}.${extension}`;
    console.log('最终文件信息:', {
      filename,
      type: compatibleBlob.type,
      size: compatibleBlob.size
    });

    // 上传处理后的音频文件
    const uploadResult = await DailyService.uploadAudio(
      compatibleBlob,
      filename
    );

    console.log('音频上传结果:', uploadResult);

    if (!uploadResult) {
      showToast('音频上传失败');
      return;
    }

    console.log('开始提交朗读记录...');

    // 然后提交朗读记录
    const formData = new FormData();
    formData.append('sentenceId', dailySentence.value.id.toString());
    formData.append('audioUrl', uploadResult.url);
    formData.append('duration', recordTime.value.toString());
    formData.append('filename', uploadResult.filename);

    console.log('提交的表单数据:', {
      sentenceId: dailySentence.value.id,
      audioUrl: uploadResult.url,
      duration: recordTime.value,
      filename: uploadResult.filename
    });

    const result = await DailyService.submitDailyReading(formData);

    console.log('朗读记录提交结果:', result);

    if (result) {
      showToast('提交成功！');

      // 重置状态
      hasRecorded.value = false;
      recordTime.value = 0;
      recordStatus.value = null;
      recordedBlob.value = null;
      audioChunks.value = [];

      // 重新加载历史记录
      await loadHistory();
    }

  } catch (error) {
    console.error('提交录音失败:', error);
    showToast('提交失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 视频上传相关函数
const selectVideo = () => {
  videoInput.value?.click();
};

const handleVideoSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];

  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('video/')) {
    showToast('请选择视频文件');
    return;
  }

  // 验证文件大小 (50MB)
  const maxSize = 50 * 1024 * 1024;
  if (file.size > maxSize) {
    showToast('视频文件不能超过 50MB');
    return;
  }

  selectedVideo.value = file;

  // 创建预览URL
  if (videoPreviewUrl.value) {
    URL.revokeObjectURL(videoPreviewUrl.value);
  }
  videoPreviewUrl.value = URL.createObjectURL(file);

  // 获取视频时长
  getVideoDuration(file);

  console.log('选择的视频文件:', {
    name: file.name,
    size: file.size,
    type: file.type
  });
};

// 获取视频时长
const getVideoDuration = (file: File) => {
  const video = document.createElement('video');
  video.preload = 'metadata';

  video.onloadedmetadata = () => {
    videoDuration.value = Math.round(video.duration);
    console.log('视频时长:', videoDuration.value, '秒');
    URL.revokeObjectURL(video.src);
  };

  video.onerror = () => {
    console.error('无法获取视频时长');
    videoDuration.value = 0;
    URL.revokeObjectURL(video.src);
  };

  video.src = URL.createObjectURL(file);
};

const reSelectVideo = () => {
  selectedVideo.value = null;
  videoDuration.value = 0;
  uploadedVideoUrl.value = '';
  if (videoPreviewUrl.value) {
    URL.revokeObjectURL(videoPreviewUrl.value);
    videoPreviewUrl.value = '';
  }
  if (videoInput.value) {
    videoInput.value.value = '';
  }
};

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const formatDuration = (seconds: number): string => {
  if (seconds === 0) return '0秒';
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  if (minutes === 0) {
    return `${remainingSeconds}秒`;
  } else {
    return `${minutes}分${remainingSeconds}秒`;
  }
};

const submitVideo = async () => {
  if (!selectedVideo.value) {
    showToast('请先选择视频文件');
    return;
  }

  if (!dailySentence.value) {
    showToast('每日一句数据加载失败');
    return;
  }

  if (videoDuration.value === 0) {
    showToast('正在获取视频信息，请稍后重试');
    return;
  }

  try {
    isSubmitting.value = true;
    console.log('开始上传视频文件...');

    const filename = `daily_${dailySentence.value.id}_${Date.now()}.${selectedVideo.value.name.split('.').pop()}`;
    console.log('视频文件信息:', {
      filename,
      type: selectedVideo.value.type,
      size: selectedVideo.value.size,
      duration: videoDuration.value
    });

    // 第一步：上传视频文件到 /upload/video
    console.log('🔄 开始调用 DailyService.uploadVideo...');
    const uploadResult = await DailyService.uploadVideo(
      selectedVideo.value,
      filename
    );

    console.log('📤 视频上传结果:', uploadResult);
    console.log('📤 上传结果类型:', typeof uploadResult);
    console.log('📤 上传结果是否有url:', uploadResult?.data?.url);

    if (uploadResult && uploadResult.data.url) {
      console.log('✅ 视频上传成功，获得URL:', uploadResult.data.url);
      uploadedVideoUrl.value = uploadResult.data.url;

      // 第二步：提交每日一句记录到 /daily/submit，包含视频URL和时长
      console.log('🔄 开始调用 DailyService.submitDailyVideo...');
      console.log('📝 提交数据:', {
        sentenceId: dailySentence.value.id,
        videoUrl: uploadResult.data.url,
        duration: videoDuration.value,
        submissionDate: new Date().toISOString().split('T')[0]
      });

      const submitResult = await DailyService.submitDailyVideo({
        sentenceId: dailySentence.value.id,
        videoUrl: uploadResult.data.url,
        duration: videoDuration.value,
        submissionDate: new Date().toISOString().split('T')[0]
      });

      console.log('📝 提交结果:', submitResult);

      if (submitResult) {
        showToast('提交成功！');
        console.log('✅ 每日一句记录提交成功');
        // 重置状态
        reSelectVideo();
        // 刷新历史记录
        await loadHistory();
      } else {
        showToast('记录提交失败，请重试');
        console.log('❌ 每日一句记录提交失败');
      }
    } else {
      showToast('视频上传失败，请重试');
      console.error('❌ 视频上传失败，未获得URL，uploadResult:', uploadResult);
    }
  } catch (error) {
    console.error('视频提交失败:', error);
    showToast('提交失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
};

// 查看历史记录
const viewAllHistory = () => {
  router.push('/daily/history');
};

// 查看单条记录
const viewRecord = (record: DailyHistory) => {
  console.log('查看记录详情:', record);
  showToast(`查看 ${formatDate(record.createdAt)} 的记录`);
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${month}月${day}日`;
};

// 获取分数类型（用于van-tag的type属性）
const getScoreType = (score: string) => {
  const numScore = parseFloat(score);
  if (numScore >= 90) return 'success';
  if (numScore >= 80) return 'primary';
  if (numScore >= 70) return 'warning';
  return 'danger';
};

// 获取等级样式类
const getLevelClass = (level: string) => {
  switch (level) {
    case '优秀':
      return 'level-excellent';
    case '良好':
      return 'level-good';
    case '一般':
      return 'level-average';
    case '较差':
      return 'level-poor';
    default:
      return 'level-default';
  }
};

// 初始化
onMounted(async () => {
  // 设置当前日期
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  currentDate.value = `${year}年${month}月${day}日`;

  // 加载数据
  await loadDailySentence();
  await loadHistory();
});

// 清理定时器和录制资源
onUnmounted(() => {
  if (recordTimer.value) {
    clearInterval(recordTimer.value);
  }

  // 停止录制并清理资源
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    mediaRecorder.value.stop();
  }

  // 清理音频播放器
  if (audioPlayer.value) {
    audioPlayer.value.destroy();
    audioPlayer.value = null;
  }
  isPlaying.value = false;

  // 清理视频预览URL
  if (videoPreviewUrl.value) {
    URL.revokeObjectURL(videoPreviewUrl.value);
  }
});
</script>

<style lang="scss" scoped>
.daily-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.daily-content {
  padding: 4vw;
  padding-bottom: 20vw; // 为底部导航留空间
}

// 日期区域
.date-section {
  margin-bottom: 6vw;

  .date-card {
    // background: linear-gradient(135deg, #1989fa 0%, #1677ff 100%);
    background-color: #fff;
    border-radius: 4vw;
    padding: 6vw;
    text-align: center;
    color: #000;
    // box-shadow: 0 2vw 8vw rgba(25, 137, 250, 0.3);

    .date-text {
      font-size: 5vw;
      font-weight: bold;
      margin-bottom: 1vw;
    }

    .date-subtitle {
      font-size: 3.5vw;
      opacity: 0.9;
      color: #888;
    }
  }
}

// 句子区域
.sentence-section {
  margin-bottom: 6vw;

  .sentence-card {
    background: white;
    border-radius: 4vw;
    padding: 6vw;
    box-shadow: 0 2vw 8vw rgba(0, 0, 0, 0.08);

    .sentence-header {
      display: flex;
      align-items: center;
      margin-bottom: 4vw;

      .sentence-icon {
        font-size: 5vw;
        color: #1989fa;
        margin-right: 2vw;
      }

      .sentence-title {
        font-size: 4.5vw;
        font-weight: 600;
        color: #323233;
      }
    }

    .sentence-content {
      margin-bottom: 6vw;

      .chinese-text {
        font-size: 5vw;
        font-weight: 600;
        color: #323233;
        line-height: 1.6;
        margin-bottom: 3vw;
        text-align: center;
      }

      .pinyin-text {
        font-size: 3.5vw;
        color: #969799;
        text-align: center;
        margin-bottom: 3vw;
        font-style: italic;
      }

      .english-text {
        font-size: 3.2vw;
        color: #646566;
        line-height: 1.5;
        text-align: center;
        padding: 3vw;
        background: #f7f8fa;
        border-radius: 2vw;
      }
    }

    .play-section {
      text-align: center;

      :deep(.van-button) {
        width: 60%;
        height: 12vw;
        border-radius: 6vw;
        font-size: 4vw;
        transition: all 0.3s ease;

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }

      .audio-tips {
        margin-top: 2vw;
        font-size: 3vw;
        color: #999;
        text-align: center;
      }
    }
  }
}

// 录制区域
.record-section {
  margin-bottom: 6vw;

  .record-card {
    background: white;
    border-radius: 4vw;
    padding: 6vw;
    box-shadow: 0 2vw 8vw rgba(0, 0, 0, 0.08);

    .record-header {
      display: flex;
      align-items: center;
      margin-bottom: 4vw;

      .record-icon {
        font-size: 5vw;
        color: #1989fa;
        margin-right: 2vw;
      }

      .record-title {
        font-size: 4.5vw;
        font-weight: 600;
        color: #323233;
      }
    }

    .record-content {
      .record-tips {
        background: #f0f9ff;
        border-radius: 2vw;
        padding: 4vw;
        margin-bottom: 4vw;

        p {
          margin: 0 0 2vw 0;
          font-size: 3.2vw;
          color: #1989fa;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }

      .record-status {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4vw;
        padding: 3vw;
        background: #f7f8fa;
        border-radius: 2vw;

        .van-icon {
          margin-right: 2vw;
          font-size: 4vw;
        }

        span {
          font-size: 3.5vw;
          font-weight: 500;
        }
      }

      .record-buttons {
        :deep(.van-button) {
          height: 12vw;
          border-radius: 6vw;
          font-size: 4vw;
          font-weight: 600;
        }

        .recorded-actions {
          .audio-preview {
            text-align: center;
            margin-bottom: 4vw;
            padding: 3vw;
            background: #f0f9ff;
            border-radius: 2vw;
            border: 1px solid #e1f5fe;

            :deep(.van-button) {
              background: #1989fa;
              border-color: #1989fa;
              color: white;
              font-size: 3.2vw;
              height: 8vw;
              min-width: 25vw;
            }
          }

          .action-buttons {
            display: flex;
            align-items: center;

            :deep(.van-button) {
              flex: 1;
              height: 10vw;
              font-size: 3.5vw;
            }
          }
        }
      }
    }
  }
}

// 历史记录区域
.history-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4vw;

    h3 {
      font-size: 4.5vw;
      font-weight: 600;
      color: #323233;
      margin: 0;
    }
  }

  // 统计信息样式
  .statistics-section {
    display: flex;
    justify-content: space-around;
    background: #f7f8fa;
    border-radius: 3vw;
    padding: 4vw;
    margin-bottom: 4vw;

    .stat-item {
      text-align: center;
      flex: 1;

      .stat-label {
        display: block;
        font-size: 3vw;
        color: #969799;
        margin-bottom: 1.5vw;
      }

      .stat-value {
        display: block;
        font-size: 4.5vw;
        font-weight: 600;
        color: #1989fa;
      }
    }
  }

  .empty-history {
    padding: 8vw 0;
    text-align: center;
  }

  .history-list {
    background: white;
    border-radius: 4vw;
    overflow: hidden;
    box-shadow: 0 2vw 8vw rgba(0, 0, 0, 0.08);

    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4vw 6vw;
      border-bottom: 1px solid #ebedf0;
      cursor: pointer;
      transition: background-color 0.2s;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background-color: #f7f8fa;
      }

      .history-content {
        flex: 1;
        margin-right: 4vw;

        .history-sentence {
          font-size: 3.8vw;
          color: #323233;
          margin-bottom: 1.5vw;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .history-date {
          font-size: 3vw;
          color: #969799;
        }
      }

      .history-score {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 1.5vw;

        .score-tag {
          :deep(.van-tag) {
            font-size: 3vw;
            padding: 1vw 2vw;
            font-weight: 600;
          }
        }

        .level-badge {
          font-size: 2.8vw;
          padding: 1vw 2vw;
          border-radius: 1.5vw;
          font-weight: 500;

          &.level-excellent {
            background: #f0f9ff;
            color: #1989fa;
          }

          &.level-good {
            background: #f6ffed;
            color: #52c41a;
          }

          &.level-average {
            background: #fff7e6;
            color: #fa8c16;
          }

          &.level-poor {
            background: #fff2f0;
            color: #ff4d4f;
          }

          &.level-default {
            background: #f7f8fa;
            color: #969799;
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 375px) {
  .daily-content {
    padding: 3vw;
  }

  .sentence-content .chinese-text {
    font-size: 4.5vw;
  }
}

/* 视频上传样式 */
.video-upload-section {
  margin-top: 4vw;
}

.upload-button-container {
  text-align: center;
}

.upload-tips {
  margin-top: 2vw;
  font-size: 3vw;
  color: #999;
  text-align: center;
}

.video-preview-section {
  margin-top: 4vw;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 2vw;
  margin-bottom: 3vw;
  padding: 3vw;
  background: #f7f8fa;
  border-radius: 2vw;
}

.video-name {
  flex: 1;
  font-size: 3.5vw;
  color: #333;
  font-weight: 500;
}

.video-details {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 1vw;
}

.video-size {
  font-size: 3vw;
  color: #999;
}

.video-duration {
  font-size: 3vw;
  color: #1989fa;
  font-weight: 500;
}

.video-preview {
  width: 100%;
  max-height: 50vw;
  border-radius: 2vw;
  background: #000;
  margin-bottom: 4vw;
}

.video-actions {
  display: flex;
  gap: 3vw;
  justify-content: center;
}
</style>
